package com.fuh.study.概率;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.Validate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @创建人 fuh
 * @创建时间 2021/4/16  17:55
 * @描述
 */
public class RateRandomUtil {
    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            RateRandomRequest request1 = new RateRandomRequest("ID1", new BigDecimal("1.66"), new BigDecimal("1.66"), 80);
            RateRandomRequest request2 = new RateRandomRequest("ID2", new BigDecimal("6.66"), new BigDecimal("6.66"), 15);
            RateRandomRequest request3 = new RateRandomRequest("ID3", new BigDecimal("9.99"), new BigDecimal("9.99"), 5);
            List<RateRandomRequest> rateRandomRequests = Arrays.asList(request1, request2, request3);

            // 验证参数
            Validate.isTrue(rateRandomRequests.stream().noneMatch(rate->rate.getPercent()<0 || rate.getPercent()>100), "百分比必须在[0,100]之间");
            Validate.isTrue(rateRandomRequests.stream().map(RateRandomRequest::getPercent).reduce(0, Integer::sum) == 100, "百分比之和必须为100");
            // 根据比例值进行划分范围
            AtomicInteger scopeMax = new AtomicInteger(0);
            rateRandomRequests.forEach(request->{
                request.setPercentScopeMin(scopeMax.getAndAdd(request.getPercent()));
                request.setPercentScopeMax(request.getPercentScopeMin()+request.getPercent()-1);
            });
            // 从【0-99】中随机取值
            int randomIntValue = RandomUtils.nextInt(0, 100);
            // 从刚划分的比例范围中定位位置
            AtomicReference<BigDecimal> discountAmt = new AtomicReference<>(BigDecimal.ZERO);
            rateRandomRequests.stream().filter(rate->rate.getPercentScopeMin()<=randomIntValue && rate.getPercentScopeMax()>=randomIntValue).findAny().ifPresent(rate->{
                discountAmt.set(produceRandomNumber(rate.getAmtScopeMin(), rate.getAmtScopeMax()));
            });
            System.out.println("随机立减金额："+discountAmt);
        }
    }

    /**
     * 产生随机数
     * @param min 最小值
     * @param max 最大值
     * @return 随机结果
     */
    public static BigDecimal produceRandomNumber(BigDecimal min, BigDecimal max) {
        BigDecimal scale = new BigDecimal(String.valueOf(Math.pow(10, Math.max(min.scale(), max.scale()))));
        long randomValue = RandomUtils.nextLong(min.multiply(scale).longValue(), max.multiply(scale).longValue());
        return new BigDecimal(String.valueOf(randomValue)).divide(scale);
    }
}
